package com.hmjk.health.map;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.Map.Entry;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BaiduMap.OnMarkerClickListener;
import com.baidu.mapapi.map.BaiduMapOptions;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.Overlay;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.PolylineOptions;
import com.baidu.mapapi.map.MyLocationConfiguration.LocationMode;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeOption;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.baidu.mapapi.utils.DistanceUtil;
import com.baidu.mapapi.navi.BaiduMapAppNotSupportNaviException;  
import com.baidu.mapapi.navi.BaiduMapNavigation;  
import com.baidu.mapapi.navi.NaviParaOption;  

import com.hmjk.health.HealthApp;
import com.hmjk.health.R;
import com.hmjk.health.background.DataManager;
import com.hmjk.health.card.CardsActivity;
import com.hmjk.health.util.DEV_DATA;
import com.hmjk.health.util.DEV_FACE;
import com.hmjk.health.util.DEV_SET;
import com.hmjk.health.util.LOCATION_INFO;
import com.hmjk.health.util.LOCATION_INFO.LOC_DETAIL;
import com.hmjk.health.views.RoundImageView;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Shader.TileMode;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

import android.text.format.Time;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

public class MapActivity extends Activity implements OnClickListener,OnMarkerClickListener{
	private static final int MSG_LOADING_TIMEOUT = 223;	
	private static final int MSG_UPDATE_DEV_DISPLAY = 224;		
	private static final int MSG_REMOVE_FAKE_REFRESH = 225;		
	
	private HealthApp mApp = null;
	private ArrayList<DEV_DATA> mDevListData = new ArrayList<DEV_DATA>();
	//private HashMap<String, Site> siteStore = new HashMap<String, Site>();	
	private HashMap<String, LOC_DETAIL> siteStore = new HashMap<String, LOC_DETAIL>();		
	private HashMap<String, devDis> disStore = new HashMap<String, devDis>();		
	private String mSelectTid = null;
	private ImageView selPhoto = null;
	private MapView mMapView = null;
	private BaiduMap mBaiduMap = null;
	private SDKReceiver sdkReceiver;
	
	// 定位相关
	LocationClient mLocClient;
	public MyLocationListenner myListener = new MyLocationListenner();
	private LocationMode mCurrentMode = LocationMode.NORMAL;
	BitmapDescriptor mCurrentMarker;

	/**
	 * 构造广播监听类，监听 SDK key 验证以及网络异常广播
	 */
	public class SDKReceiver extends BroadcastReceiver {
		public void onReceive(Context context, Intent intent) {
			String s = intent.getAction();
			//TextView text = (TextView) findViewById(R.id.text_Info);
			//text.setTextColor(Color.RED);
			if (s.equals(SDKInitializer.SDK_BROADTCAST_ACTION_STRING_PERMISSION_CHECK_ERROR)) {
				//text.setText("key 验证出错! 请在 AndroidManifest.xml 文件中检查 key 设置");
			} else if (s
					.equals(SDKInitializer.SDK_BROADCAST_ACTION_STRING_NETWORK_ERROR)) {
				//text.setText("网络出错");
			}
		}
	}	
	
	private LayoutInflater inflater;
	private RoundImageView mPic;	
	private LinearLayout devLL;
	private ImageButton backBut;
	private ImageButton refreshBut;
	private LinearLayout allLL;
	private LinearLayout singleDevLL;
	//private TextView titleLocTip;
	private ImageView sosOnTitle;
	private TextView titleLocTxt;	
	private TextView NameTxt;
	private TextView updateTimeTxt;	
	private ImageView backGroupModeBut;
	private Button detailBut;
	private Button navBut;
	private Button callBut;
	//private ImageView loadingImg;	
	private Animation cycleAnim;
	private LinearLayout sigleModeButPan;
	
	private Matrix mMatrix;  
	private BitmapShader mBitmapShader; 
	private Paint mBitmapPaint; 
	private HashMap<String, Bitmap> mFaceMarkerMap = new HashMap<String, Bitmap>();
	
	//these two value are based on pixel size of resource png image
	private final int MARKER_BG_PHOTO_TOP = 14; //pixels
	private final int MARKER_BG_RES_W = 130;//pixels
	private final float MARKER_BG_PHOTO_SCALE = 0.618f;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        mApp = (HealthApp)getApplication();        
        initBitmapDatas();
	//	Intent i = getIntent();

        BaiduMapOptions mapOptions = new BaiduMapOptions();
        mapOptions.zoomControlsEnabled(false);//隐藏缩放按钮
        mapOptions.scaleControlEnabled(false);
        mapOptions.scrollGesturesEnabled(true);
        mMapView = new MapView(this, mapOptions);// 获取地图控件引用
        setContentView(mMapView);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
        View view = LayoutInflater.from(this).inflate(R.layout.activity_map,null);//自己的xml
        this.addContentView(view, params);		
		
        //setContentView(R.layout.activity_map);
		inflater = getLayoutInflater();      
		devLL = (LinearLayout)findViewById(R.id.attentionList);
		backBut = (ImageButton)findViewById(R.id.back);
		backBut.setOnClickListener(this);
		refreshBut = (ImageButton)findViewById(R.id.refresh);
		refreshBut.setOnClickListener(this);
		allLL = (LinearLayout)findViewById(R.id.all_cover);
		singleDevLL = (LinearLayout)findViewById(R.id.sigle_cover);
		  //titleLocTip = (TextView)findViewById(R.id.curLocationTip);
		sosOnTitle = (ImageView) findViewById(R.id.sos);
		  titleLocTxt = (TextView)findViewById(R.id.curLocationTxt);	
		  NameTxt = (TextView)findViewById(R.id.selnameTxt);
		  updateTimeTxt = (TextView)findViewById(R.id.updateTimeTxt);			
		 backGroupModeBut = (ImageView)findViewById(R.id.allCoverIcon);
		 detailBut = (Button)findViewById(R.id.detailBut);
		 navBut = (Button)findViewById(R.id.navigateBut);
		 callBut = (Button)findViewById(R.id.callBut);	
		 backGroupModeBut.setOnClickListener(this);
		 detailBut.setOnClickListener(this);
		 navBut.setOnClickListener(this);
		 callBut.setOnClickListener(this);
		 sigleModeButPan = (LinearLayout)findViewById(R.id.buttonpannel);
		 selPhoto = (ImageView) findViewById(R.id.selPersonphoto);
		 //loadingImg = (ImageView)findViewById(R.id.loading);
		 cycleAnim = AnimationUtils.loadAnimation(this, R.anim.rotatecycled);
		
        //mMapView = (MapView)findViewById(R.id.bmapsView);
        mBaiduMap = mMapView.getMap();
        


		
		mPic = (RoundImageView)this.findViewById(R.id.myphoto);
		mPic.setOnClickListener(this);
				
		Bitmap bitmap = (Bitmap) mApp.getDataManager().checkData(DataManager.F_USERFACE, null);
		if((bitmap != null) && !bitmap.isRecycled()){
			mPic.setImageBitmap(bitmap);
		}else{
			mPic.setImageResource(R.drawable.default_photo);
		}
		

		// 注册 SDK 广播监听者
		IntentFilter iFilter = new IntentFilter();
		iFilter.addAction(SDKInitializer.SDK_BROADTCAST_ACTION_STRING_PERMISSION_CHECK_ERROR);
		iFilter.addAction(SDKInitializer.SDK_BROADCAST_ACTION_STRING_NETWORK_ERROR);
		sdkReceiver = new SDKReceiver();
		registerReceiver(sdkReceiver, iFilter);		
		
		//注册数据更新监听者
		IntentFilter filter = new IntentFilter();
		//filter.addAction(HealthApp.ACTION_SIGN_IN_OUT);
		filter.addAction(DataManager.DATA_UPDATE_ACTION);
		//filter.addAction(DataManager.DATA_COMMIT_RESULT);
		registerReceiver(mReceiver, filter);

		// 开启定位图层
		mBaiduMap.setMyLocationEnabled(true);
		// 定位初始化
		mLocClient = new LocationClient(mApp.getApplicationContext());
		mLocClient.registerLocationListener(myListener);
		LocationClientOption option = new LocationClientOption();
		option.setOpenGps(true);// 打开gps
		option.setCoorType("bd09ll"); // 设置坐标类型
		option.setScanSpan(5000);
		 option.setLocationNotify(true);
		mLocClient.setLocOption(option);
		mLocClient.start();
		mLocClient.requestLocation();		
		
		mBaiduMap.setMyLocationConfigeration(new MyLocationConfiguration(mCurrentMode, true, BitmapDescriptorFactory.fromResource(R.drawable.empty)));	
		
		mBaiduMap.setOnMarkerClickListener(this);
		
		retrieveDeviceListData(); 
		for(DEV_DATA dev : mDevListData )
		{
			View convertView = inflater.inflate(R.layout.map_person, null);
			RoundImageView lView = (RoundImageView)convertView.findViewById(R.id.photo);
			String[] faceargs = new String[1];
			faceargs[0] = dev.id;
			DEV_FACE face = (DEV_FACE) mApp.getDataManager().checkData(DataManager.F_DEVICEFACE, faceargs);
			if(face == null){
				lView.setImageResource(R.drawable.default_photo);
			}else if((face.bitmap != null) && !face.bitmap.isRecycled()){
				lView.setImageBitmap(face.bitmap);
			}else{
				lView.setImageResource(R.drawable.default_photo);
			}
			lView.setOnClickListener(roundViewClickListener);
			lView.setTag(dev.id);
			devLL.addView(convertView);				
		}
	
		if(!this.isSingleTidMapMode){
			enterAllSiteMode();
		}
	}

	private long mylocUpdateTime = 0; 
	private Marker mySiteMarker = null;
	
	private boolean isFirstLoc = true;
	public class MyLocationListenner implements BDLocationListener {

		@Override
		public void onReceiveLocation(BDLocation location) {
			// map view 销毁后不在处理新接收的位置
			if (location == null || mMapView == null)
				return;
			
			if(!isFirstLoc)
				return;
			
			isFirstLoc = false;
			
			MyLocationData locData = new MyLocationData.Builder()
					.accuracy(/*location.getRadius()*/0)
					// 此处设置开发者获取到的方向信息，顺时针0-360
					.direction(/*100*/0).latitude(location.getLatitude())
					.longitude(location.getLongitude()).build();
			        mBaiduMap.setMyLocationData(locData);
			        
			    mylocUpdateTime = System.currentTimeMillis();    
                if(mySiteMarker != null)
                	mySiteMarker.remove();
                
				LatLng ll = new LatLng(location.getLatitude(),
						location.getLongitude());
				
				mySiteMarker = createMarkerAndShow(ll, "mySite");
				
				scaleMgr.myloc = ll;
				
				//scaleMgr.updateDisInSiteStore();
				scaleMgr.updateMap();	
				
				//MapStatusUpdate u = MapStatusUpdateFactory.newLatLng(ll);
				//mBaiduMap.animateMapStatus(u);
				
		}
	}

	private void initBitmapDatas(){
		mMatrix = new Matrix(); 
		mBitmapPaint = new Paint(); 
		mBitmapPaint.setAntiAlias(true); 
	}
	
	private Bitmap addface(int resbg, Bitmap face){
		Bitmap bg = BitmapFactory.decodeResource(getResources(), resbg);
		if(bg == null)
			return null;
		
		int facew = face.getWidth();
		int faceh = face.getHeight();
		int bgw = bg.getWidth();
		
		float bg_scale = bgw * 1.0f /MARKER_BG_RES_W;
		//int bh = bg.getHeight();
		int fbitmap_w = (int) (MARKER_BG_PHOTO_SCALE * bgw);
		
		Bitmap fbitmap = Bitmap.createBitmap(fbitmap_w, fbitmap_w, Bitmap.Config.ARGB_8888);
		mBitmapShader = new BitmapShader(face, TileMode.CLAMP, TileMode.CLAMP); 
		
		int faceSize = Math.min(facew, faceh); 
		float scale = fbitmap_w * 1.0f/ faceSize; 
	    int r = fbitmap_w/2;
	    mMatrix.setScale(scale, scale); 
		mBitmapShader.setLocalMatrix(mMatrix); 
		mBitmapPaint.setShader(mBitmapShader); 
		Canvas fcanvas = new Canvas(fbitmap);
		fcanvas.drawCircle(fbitmap_w/2, fbitmap_w/2, r, mBitmapPaint); 
		
		fbitmap_w = fbitmap.getWidth();
		
		Bitmap bitmap = Bitmap.createBitmap(bgw, bgw, Bitmap.Config.ARGB_8888);
		Canvas canvas = new Canvas(bitmap);
		canvas.drawBitmap(bg, 0, 0, null);
		canvas.drawBitmap(fbitmap, (bgw-fbitmap_w)/2, (bg_scale * MARKER_BG_PHOTO_TOP), null);
		fbitmap.recycle();
		System.gc();
		/*try{
			Canvas canvas = new Canvas(bitmap);
			canvas.drawBitmap(bg, 0, 0, null);
			canvas.save();
			canvas.scale(scale, scale);
			canvas.drawCircle(bw/2, bw/2, r, mBitmapPaint); 
			canvas.restore();
		}catch(Exception e){
			e.printStackTrace();
			if(!bitmap.isRecycled())
				bitmap.recycle();
			bitmap = null;
		}*/
		
		return bitmap;
	}
	
	private void releaseAllFaceMark(){
		if(mFaceMarkerMap.isEmpty())
			return;
		
		Iterator<Entry<String, Bitmap>> iter = mFaceMarkerMap.entrySet().iterator();
		while(iter.hasNext()){
			Entry<String,Bitmap> entry = (Entry<String,Bitmap>) iter.next();
			String key = entry.getKey();
			Bitmap bitmap = entry.getValue();
			if((bitmap != null) && (!bitmap.isRecycled())){
				bitmap.recycle();
			}
		}		
		System.gc();
	}
	
	private void createMarkerBitmap(String tid, int resbg){
		Bitmap face = null;
		if(tid.equals("mySite")){
			face = (Bitmap) mApp.getDataManager().checkData(DataManager.F_USERFACE, null);
		}else{
			String[] fargs = new String[1];
			fargs[0] = tid;
			DEV_FACE fdata = (DEV_FACE) mApp.getDataManager().checkData(DataManager.F_DEVICEFACE, fargs);
			if(fdata == null){
				face = null;
			}else if((fdata.bitmap != null) && !fdata.bitmap.isRecycled()){
				face = fdata.bitmap;
			}
		}
		
		Bitmap mark = mFaceMarkerMap.get(tid);
		if((face == null) || face.isRecycled()){
			if((mark != null) && (!mark.isRecycled())){
				mark.recycle();
				System.gc();
			}
			mFaceMarkerMap.remove(tid);
		}else{
			if((mark != null) && (!mark.isRecycled())){
				return;
			}
			mFaceMarkerMap.remove(tid);
			mark = addface(resbg,face);
			if(mark != null)
				mFaceMarkerMap.put(tid, mark);
		}	
	}
	
    private Marker createMarkerAndShow(LatLng ll, String tid)
    {
    	if(tid.equals("mySite"))
    	{
    		Bitmap fmark = mFaceMarkerMap.get(tid);
    		if(fmark == null){
    			createMarkerBitmap(tid,R.drawable.map_marker_me);
    			fmark = mFaceMarkerMap.get(tid);
    		}
			
			if((fmark != null) && (!fmark.isRecycled())){
				OverlayOptions ooA = new MarkerOptions().position(ll).icon(BitmapDescriptorFactory.fromBitmap(fmark));
		        Marker mark = (Marker) (mBaiduMap.addOverlay(ooA));	
		        mark.setTitle("mySite");
		        return mark;
			}else{
		        OverlayOptions ooA = new MarkerOptions().position(ll).icon(BitmapDescriptorFactory.fromResource(R.drawable.map_marker_me));
		        Marker mark = (Marker) (mBaiduMap.addOverlay(ooA));	
		        mark.setTitle("mySite");
		        return mark;
    		}
    	}
    	else
    	{
    		Bitmap fmark = mFaceMarkerMap.get(tid);
    		if(fmark == null){
    			createMarkerBitmap(tid,R.drawable.map_marker_dev);
    			fmark = mFaceMarkerMap.get(tid);
    		}
    		
    		if((fmark != null) && (!fmark.isRecycled())){
				OverlayOptions ooA = new MarkerOptions().position(ll).icon(BitmapDescriptorFactory.fromBitmap(fmark));
		        Marker mark = (Marker) (mBaiduMap.addOverlay(ooA));	
		        mark.setTitle(tid);
		        return mark;
			}else{
		        OverlayOptions ooA = new MarkerOptions().position(ll).icon(BitmapDescriptorFactory.fromResource(R.drawable.map_marker_dev));
		        Marker mark = (Marker) (mBaiduMap.addOverlay(ooA));	
		        mark.setTitle(tid);
		        return mark;    		
			}
    	}
    }
	
    private void enterAllSiteMode()
    {
    	clearPolyline();
    	this.storeClear();
    	
    	mBaiduMap.setMyLocationEnabled(true);
    	mLocClient.start(); 
    	mLocClient.requestLocation();
    	isFirstLoc = true;
    	if(scaleMgr.myloc != null && mySiteMarker == null)
    	{
    		mySiteMarker = createMarkerAndShow(scaleMgr.myloc, "mySite");
    	}
    	this.isSingleTidMapMode = false;
    	this.singleDevLL.setVisibility(View.GONE);
    	//this.titleLocTip.setVisibility(View.GONE);
    	sosOnTitle.setVisibility(View.GONE);
    	this.titleLocTxt.setVisibility(View.GONE);
    	this.allLL.setVisibility(View.VISIBLE);
    	this.refreshBut.setVisibility(View.VISIBLE);
    	   
    	if(this.mDevListData.isEmpty())
    		return;
    	
    	this.checkSiteInfo();
    	startRefreshSiteInfo();

    }	

    private void clearDisStore()
    {
    	Iterator iterator = disStore.keySet().iterator();    	
    	while(iterator.hasNext()) {
    	//System.out.println(hm.get(iterator.next()));      		
    		devDis dd = disStore.get(iterator.next());
    		dd.mark.remove();
    		//devLL.removeView(dd.viewInLL);
    	}    	
    }
    private void storeClear()
    { 	
    	//devLL.removeAllViews();
    	//mBaiduMap.clear();
    	clearDisStore();
    	disStore.clear();    	
    	siteStore.clear();
    	scaleMgr.clearPoint();

    } 
	
	private void checkSiteInfo()   //get data from ram not net
	{
		
		if(mDevListData.isEmpty())
			return;
		
		int count = mDevListData.size();
		String[] args = new String[count];
		int i = 0;
		for(DEV_DATA dev : mDevListData )
		{
			args[i] = dev.id;			
			i++;
		}
		
		LOCATION_INFO[] arr = (LOCATION_INFO[]) mApp.getDataManager().checkData(DataManager.F_DEVICE_LOCATION, args);
		
		if((arr != null) && (arr.length > 0)){
							
				for(int j = 0;j<arr.length;j++)
				{				
					LOCATION_INFO data = arr[j];
					if(data == null)
						continue;
					
				String tid = data.tid;
				
				ArrayList<LOC_DETAIL> addrList = data.getAddrList();
				if(addrList.isEmpty())
					continue;
				
				LOC_DETAIL locate = addrList.get(0);	
				siteStore.put(tid, locate);
				                

				LatLng ll = new LatLng(locate.lat,locate.lng);	
				Marker mark = this.createMarkerAndShow(ll, tid);
				
				scaleMgr.addPoint(ll);
				
				devDis dd = new devDis(tid,/*convertView,*/mark);
				disStore.put(tid, dd); 
				
				}

		}
		//scaleMgr.updateDisInSiteStore();
		scaleMgr.updateMap();
			
	}		
	
	private void retrieveDeviceListData(){
		String[] args = new String[2];
		args[0] = "DEV_SINGLE_TYPE";
		args[1] = new String(DEV_DATA.TYPE_LOCATE);
		JSONObject devjson = (JSONObject) mApp.getDataManager().checkData(DataManager.F_DEVICELIST, args);
		if(devjson != null){
			try{
				JSONArray ar = devjson.getJSONArray("array");
				int len = ar.length();
				
				mDevListData.clear();
				int index = 0;
				for(int i = 0; i < len; i++){
					JSONObject e = ar.getJSONObject(i);
					DEV_DATA d = new DEV_DATA();
					
					d.id = e.getString("tid");
					d.name = e.getString("name");
						
					String ss = e.getString("status");
					d.status = Integer.parseInt(ss);
						
					d.type = e.getString("type");
						
					String a = e.getString("admin");
					d.admin = Integer.parseInt(a);
						
					d.index = index;
						
					mDevListData.add(d);
					index ++;
				}

			} catch (JSONException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		}
	}	

	@Override
    public boolean onKeyDown(int keyCode, KeyEvent event){
		if(keyCode == KeyEvent.KEYCODE_BACK){
			if(isSingleTidMapMode){
				enterAllSiteMode();
				return true;
			}
		}
		
		return super.onKeyDown(keyCode,event);
	}
	
	@Override
	public void onResume(){
		mMapView.onResume();
		super.onResume();
		

		
		//upateCard();
	}
	
	@Override
	public void onPause(){
		mMapView.onPause();
		super.onPause();

		//mhandler.removeMessages(MSG_LOADING_TIMEOUT);
	}

	//发出查询指令
	private int refreshIndex = 0;
	private boolean isRefreshing = false;
	private long latestRefreshEndTime = 0;
    private void refreshSiteInfo()
    {

		
		boolean sendSuc = false;
		
		while(sendSuc == false && refreshIndex < mDevListData.size())
		{
		DEV_DATA dev = mDevListData.get(refreshIndex);
		
		if(dev != null && dev.id != null)
		{			
			sendSuc = mApp.getDataManager().refreshData(DataManager.F_DEVICE_LOCATION,dev.id);
		}
		
		if(sendSuc == true)
			break;
		else
		{
			refreshIndex ++;
		}
		
		}
		
		if(refreshIndex >= mDevListData.size())
		{	
			
			refreshBut.clearAnimation();
			//loadingImg.setVisibility(View.GONE);
			isRefreshing = false;
			this.refreshBut.setEnabled(true);
			latestRefreshEndTime = System.currentTimeMillis();
		}		
    }	
	
    private void refreshSingleSiteInfo(String tid)
    {
		
		boolean sendSuc = false;					
	   sendSuc = mApp.getDataManager().refreshData(DataManager.F_DEVICE_LOCATION,tid);
	   
		if(!sendSuc)
		{				
			refreshBut.clearAnimation();
			//loadingImg.setVisibility(View.GONE);
			isRefreshing = false;
			this.refreshBut.setEnabled(true);
		}
		
    }	
    private boolean startRefreshSiteInfo()
    {
        if(isRefreshing)
        	return false;
		if(mDevListData.isEmpty())
			return false;  
		
		long intervel = System.currentTimeMillis() - this.latestRefreshEndTime;
		if(intervel < 10 * 1000)
		{
			refreshBut.startAnimation(cycleAnim);		
			
			this.refreshBut.setEnabled(false);
			Message m = mhandler.obtainMessage(MSG_REMOVE_FAKE_REFRESH);
			this.mhandler.sendMessageDelayed(m, 5*1000);
			return true;
		}
		isRefreshing = true;
		
		//loadingImg.setVisibility(View.VISIBLE);
		//loadingImg.setImageResource(R.drawable.wait_small);
		refreshBut.startAnimation(cycleAnim);		
		
		this.refreshBut.setEnabled(false);
		if(this.isSingleTidMapMode)
		{
			refreshSingleSiteInfo(mSelectTid);
		}
		else
		{
        refreshIndex = 0;
        refreshSiteInfo();
		}
        return true;
    }

    
	private BroadcastReceiver mReceiver = new BroadcastReceiver(){
		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if(action.equals(DataManager.DATA_UPDATE_ACTION)){
				String t = intent.getStringExtra("type");
				boolean s = intent.getBooleanExtra("state", false);		
				
				if(t.equals(DataManager.F_DEVICE_LOCATION) && (s == false))
				{
					refreshIndex ++;
					refreshSiteInfo();
					return;
				}


				if(t.equals(DataManager.F_DEVICE_LOCATION) && s == true){
					String tid = intent.getStringExtra("tid");
					if(tid.isEmpty())
						return;	
					
					if(!isSingleTidMapMode)
					{	
					String[] args = new String[1];
					args[0] = tid;
					
					LOCATION_INFO[] arr = (LOCATION_INFO[]) mApp.getDataManager().checkData(DataManager.F_DEVICE_LOCATION, args);
					
					if((arr != null) && (arr.length > 0)){						

										
							LOCATION_INFO data = arr[0];
							if(data != null)
							{								
								ArrayList<LOC_DETAIL> addrList = data.getAddrList();
								if(addrList.isEmpty())
								{
									refreshIndex ++;
									refreshSiteInfo();
									return;
								}
																	
								LOC_DETAIL locateNew = addrList.get(0);																
								LOC_DETAIL locateOld = siteStore.get(tid);
																
								if(locateOld != null)
								{
									LatLng ll = new LatLng(locateOld.lat,locateOld.lng);
									scaleMgr.removePoint(ll);
								}
								
								siteStore.put(tid, locateNew);
								
								scaleMgr.addPoint(new LatLng(locateNew.lat,locateNew.lng));
								
								Message m = mhandler.obtainMessage(MSG_UPDATE_DEV_DISPLAY);		
								Bundle bundle = new Bundle();   
								bundle.putString("tid", tid);
								m.setData(bundle);
								mhandler.sendMessage(m);								
							}                            
					}

					refreshIndex ++;
					refreshSiteInfo();
					}
					else
					{
						if(tid.equals(mSelectTid))
						{
							scaleManager myScale = new scaleManager();												    	
					    	
							clearPolyline();
							
							ArrayList<LatLng> points = new ArrayList<LatLng>();
							
							String[] args = new String[1];
					        args[0] = tid;
							
					        LOCATION_INFO[] arr = (LOCATION_INFO[]) mApp.getDataManager().checkData(DataManager.F_DEVICE_LOCATION, args);
							
							if((arr != null) && (arr.length > 0)){
												
									LOCATION_INFO data = arr[0];
									if(data != null)
									{	
										ArrayList<LOC_DETAIL> addrList = data.getAddrList();
										if(addrList.isEmpty())
											return;
																			
									    for(int i = 0;i<addrList.size();i++)
									    {	
									       LOC_DETAIL loc = addrList.get(i);	
									       LatLng p = new LatLng(loc.lat,loc.lng);
									       if(i == 0)
									       {
										     devDis dd = disStore.get(tid);
										     if(dd != null)
										     {
											    dd.mark.remove();
											    dd.mark = createMarkerAndShow(p,tid);											
										     }
										     myScale.myloc = p;
										     points.add(p);
									        }
									        else
									        {
									           points.add(p);
									           myScale.addPoint(p);
									        }
									}
									}
							   } 
								
								if(points.size()>1){
								 
								 OverlayOptions polylineOp = new PolylineOptions().width(10)
											.color(Color.BLUE).points(points);
								 mPolyline = mBaiduMap.addOverlay(polylineOp);

								}
					    	
							myScale.updateMap();	
						   }
							
							refreshBut.clearAnimation();
							//loadingImg.setVisibility(View.GONE);
							isRefreshing = false;
							refreshBut.setEnabled(true);							
						}

				}else if(t.equals(DataManager.F_DEVICELIST)){
					//if(false == refreshDeviceList()){
					//	CardFragment cf = mFragmentMap.get(mCurDev.id);
					//	if(cf != null)
					//	cf.refreshResult(DataManager.F_DEVICELIST,s);
					//}
				}else if(t.equals(DataManager.F_DEVICEFACE)){
					//String tid = intent.getStringExtra("tid");
					//if(tid.isEmpty())
					//	tid = mCurDev.id;
					//CardFragment cf = mFragmentMap.get(tid);
					//if(cf != null)
					//cf.refreshResult(t,s);
				}
			}
		}
	};
	
	
	
	@Override
	protected void onDestroy() {
		//siteStoreClear();
		// 退出时销毁定位
		mLocClient.stop();
		// 关闭定位图层
		mBaiduMap.setMyLocationEnabled(false);		
		mMapView.onDestroy();
		
		mMapView = null;
		unregisterReceiver(mReceiver);
		unregisterReceiver(sdkReceiver);
		releaseAllFaceMark();
		super.onDestroy();
	}

	@Override
	public void onClick(View arg0) {
		// TODO Auto-generated method stub
		switch(arg0.getId()){
		case R.id.back:{
			storeClear();
			this.finish();
		}break;
		case R.id.allCoverIcon:
			enterAllSiteMode();
			break;
		case R.id.detailBut:
		{
			this.finish();
			
			Intent i = new Intent(this,CardsActivity.class);
			i.putExtra("indicated", mSelectTid);
			startActivity(i);			
		}
        break;
		case R.id.navigateBut:
		{
			if(scaleMgr.myloc != null)
			{
				
			LatLng pt1 = scaleMgr.myloc;  
		    LOC_DETAIL locate = siteStore.get(mSelectTid);
			LatLng pt2 = new LatLng(locate.lat, locate.lng);  

			NaviParaOption para = new NaviParaOption().startPoint(pt1).endPoint(pt2)  
                    .startName("起点").endName("终点");  

            try {  
                  /** 
                   * openBaiduMapNavi(NaviParaOption para, Context context) 
                   * 调起百度地图导航页面 
                   * */  
                  boolean ret = BaiduMapNavigation.openBaiduMapNavi(para, this);  

                   } catch (BaiduMapAppNotSupportNaviException e) {  
                  e.printStackTrace();  
                  
  	            AlertDialog.Builder builder = new AlertDialog.Builder(this);
  	            //builder.setTitle(R.string.SelectAApp);

  	            	builder.setMessage(R.string.baidumap_not_install);
  	            
  	                builder.setNegativeButton(this.getResources().getString(R.string.ok), new DialogInterface.OnClickListener() { 
  	                public void onClick(DialogInterface dialog, int id) { 
  	                     dialog.cancel(); 
  	                } 
  	            }); 
  	            builder.show();	  
               }  
			}
			
/*			List<PackageInfo> packs = getPackageManager().getInstalledPackages(0);	
			List<String> resInfo  = new ArrayList<String>();
			List<String> disInfo  = new ArrayList<String>();

			
	        for (PackageInfo info : packs) {   
	        	String s1 = info.packageName;
	        	if(!(s1.contains("oppo") || s1.contains("mediatek")|| s1.contains("Oppo")|| s1.contains("com.android")|| s1.contains("nearme")))
	        	{
	        		String s2 = info.packageName;	
	        	if( info.packageName.contains("navi") || info.packageName.contains("uu.uueeye")|| info.packageName.contains("tencent.map")
	        			|| info.packageName.contains("sogou.map")|| info.packageName.contains("uu.uueeye")|| info.packageName.contains("mapbarmap")
	        			|| info.packageName.contains("baidu.BaiduMap"))
	        	{
	        		String s = info.applicationInfo.loadLabel(getPackageManager()).toString();
	        		disInfo.add(s);	 
	        		resInfo.add(info.packageName);	 	        		
	        	}	 
	        	}
	        } 
	        
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle(R.string.SelectAApp);
            if(resInfo.size() == 0)
            	builder.setMessage(R.string.NoFindNavApp);
            
            builder.setNegativeButton(this.getResources().getString(R.string.Cancel), new DialogInterface.OnClickListener() { 
                public void onClick(DialogInterface dialog, int id) { 
                     dialog.cancel(); 
                } 
            }); 
            
            
            
            //    指定下拉列表的显示数据
            final String[] lunches = new String[disInfo.size()];//{"广州", "上海", "北京", "香港", "澳门"};
            final String[] apks = new String[resInfo.size()];
            for(int i = 0; i< resInfo.size();i++)
            {
            	lunches[i] = disInfo.get(i);
            	apks[i] = resInfo.get(i);
            }
            
            //    设置一个下拉的列表选择项
            builder.setItems(lunches, new DialogInterface.OnClickListener()
            {
                @Override
                public void onClick(DialogInterface dialog, int which)
                {
                   // Toast.makeText(MainActivity.this, "选择的城市为：" + cities[which], Toast.LENGTH_SHORT).show();
                	Intent LaunchIntent = getPackageManager().getLaunchIntentForPackage(apks[which]);
                	if(LaunchIntent != null)
                	startActivity(LaunchIntent);
                }
            });
            builder.show();	  */      
		}
		break;
		case R.id.callBut:
		{
			Intent intent=new Intent();
			intent.setAction(Intent.ACTION_DIAL);   //android.intent.action.DIAL
			intent.setData(Uri.parse("tel:"+ getDevPhNumber(mSelectTid)));

			startActivity(intent); 			
		}
		break;
		case R.id.refresh:
			startRefreshSiteInfo();
		break;
		case R.id.myphoto:
			enterSingleTidMapMode("mySite");
		break;
		}	
		
	}
	
    private OnClickListener roundViewClickListener = new OnClickListener() {
		public void onClick(View v) {
			String tid = (String)v.getTag();
			//if(siteStore.get(tid) != null)
			{
			mSelectTid = tid;
			enterSingleTidMapMode(tid);
			}
		}
	};
	
	@Override
	public boolean onMarkerClick(Marker arg0) {
		// TODO Auto-generated method stub
		String id = arg0.getTitle();
		mSelectTid = id;
		
		if(this.isRefreshing)
			return true;
		
		if(id.equals("mySite"))
			enterSingleTidMapMode("mySite");
		else
		{
			enterSingleTidMapMode(id);
		}
		return true;
	}		
    
	private scaleManager scaleMgr = new scaleManager();
	private class scaleManager{
	   private ArrayList<LatLng> mLocationList = new ArrayList<LatLng>();		
       public LatLng myloc = null;
       public double maxDis = 0;
       public double minDis = 0;
       public static final int lcdSize = 4;
       public final double[] mapS = { 10.0*lcdSize, 20.0*lcdSize, 50.0*lcdSize, 100.0*lcdSize, 200.0*lcdSize, 500.0*lcdSize, 1000.0*lcdSize, 2000.0*lcdSize,  
    	    5000.0*lcdSize, 10000.0*lcdSize, 20000.0*lcdSize, 25000.0*lcdSize, 50000.0*lcdSize, 100000.0*lcdSize, 200000.0*lcdSize, 500000.0*lcdSize, 1000000.0*lcdSize,  
    	    2000000.0*lcdSize};
       //{10.0,20.0,50.0,100.0,200.0,500.0,1000.0,2000.0,5000.0,10000.0,20000.0,25000.0,50000.0,100000.0,200000.0,500000.0,1000000.0,2000000.0}
       
       public void clearPoint()
       {
    	   synchronized(scaleMgr){
    	   this.mLocationList.clear();
    	   }
       }
       
       public void removePoint(LatLng nloc)
       {
    	   synchronized(scaleMgr){
    		      if(mLocationList.size() > 0)
    		      {
    		    	  boolean found = false;
    		    	  int j = 0;
    		    	  for(int i = 0;i<mLocationList.size();i++)
    		    	  {
    		    		  if(mLocationList.get(i) == nloc)
    		    		  {
    		    			  j = i;
    		    			  found = true;
    		    		      break;
    		    		  }
    		    	  }
    		    	  
    		    	  if(found == true)
    		    		  mLocationList.remove(j); 
    		      }

    	   }
       }       
       
       public void addPoint(LatLng nloc)
       {
    	   synchronized(scaleMgr){
    		   
    	   mLocationList.add(nloc);   
    	   /*if(myloc == null)
    		   return;
    	   
    	   DistanceUtil util = new DistanceUtil();
    	   double dis = util.getDistance(myloc, nloc);
    	   
    	   if(maxDis == 0)
    		   maxDis = dis;
    	   if(minDis == 0)
    		   minDis = dis;
    	   
    	   if(dis > maxDis)
    		   maxDis = dis;
    	   
    	   if(dis < minDis)
    		   minDis = dis;  */
    	   }
       }
               
       
       public void updateMap()
       {
    	   synchronized(scaleMgr){   
    		 LatLng cenpt;
    	     if(myloc == null)
    	     {
    	    	 if(mLocationList.size() == 0)
    	    		 return;
    	    	 
    		     cenpt = mLocationList.get(0);       		  
     	     }    		   
    	     else
    	     {
    		  cenpt = myloc;
    	     }
    	   
    		  for(LatLng p : this.mLocationList) 
    		  {
    	    	   DistanceUtil util = new DistanceUtil();
    	    	   double dis = util.getDistance(cenpt, p);    	
    	    	   if(maxDis == 0)
    	    		   maxDis = dis;
    	    	   if(minDis == 0)
    	    		   minDis = dis;
    	    	   
    	    	   if(dis > maxDis)
    	    		   maxDis = dis;
    	    	   
    	    	   if(dis < minDis)
    	    		   minDis = dis;    
    	       }    	    	   
    		 
    		    
    	       float f = mBaiduMap.getMaxZoomLevel();//20.0
    	       float m = mBaiduMap.getMinZoomLevel();//3.0
    	 
    	       int i = 0;
    	      while(i < mapS.length)
    	      {
    		    if(maxDis > mapS[i])
    			 i++;
    		    else
    			 break;
    	      }
    	 
    	      
    	      float s = f - i;
    	      s = (float) (s+0.5);
    	      MapStatusUpdate u = MapStatusUpdateFactory.newLatLngZoom(cenpt, s);

    	      mBaiduMap.animateMapStatus(u);   
    	   }
       }
       
	}


	
    private boolean isSingleTidMapMode = false;
    
    private void enterSingleTidMapMode(String tid)
    {
    	titleLocTxt.setText("");
    	updateTimeTxt.setText(getResources().getString(R.string.update_at,"--:--"));
    	if(tid.equals("mySite"))
    	{
    	  if( scaleMgr.myloc == null)
    		  return;
    	  
    	  clearDisStore();         	
  	      MapStatusUpdate u = MapStatusUpdateFactory.newLatLngZoom(scaleMgr.myloc, 19.0f);

  	      mBaiduMap.animateMapStatus(u);          	
        	
        	GeoCoder mSearch = GeoCoder.newInstance();
    		OnGetGeoCoderResultListener listener = new OnGetGeoCoderResultListener() {

    			@Override
    			public void onGetGeoCodeResult(GeoCodeResult arg0) {
    				// TODO Auto-generated method stub
    				
    			}

    			@Override
    			public void onGetReverseGeoCodeResult(ReverseGeoCodeResult result) {
    				// TODO Auto-generated method stub
    				String markerAddr = result.getAddress();
    				titleLocTxt.setText(markerAddr);
    				//titleLocTip.setVisibility(View.VISIBLE);
    				titleLocTxt.setVisibility(View.VISIBLE);
    				LatLng markerPoint = result.getLocation();
    			}
    			
    		};
    		mSearch.setOnGetGeoCodeResultListener(listener);
			mSearch.reverseGeoCode(new ReverseGeoCodeOption().location(scaleMgr.myloc ));

			JSONObject mData = (JSONObject) mApp.getDataManager().checkData(DataManager.F_USERDATA, null);

			
			
			if(mData != null){
				try {
					if(mData.has("nickname")){
						this.NameTxt.setText(mData.getString("nickname"));
					}
					else if(mData.has("username"))
					{
						this.NameTxt.setText(mData.getString("username"));
					}
					else if(mData.has("mobileno"))
					{
						this.NameTxt.setText(mData.getString("mobileno"));
					}
					else 
					{
						NameTxt.setText(R.string.Me);
					}
				} catch (JSONException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
			}
			
			Bitmap bitmap = (Bitmap) mApp.getDataManager().checkData(DataManager.F_USERFACE, null);
			if((bitmap != null) && !bitmap.isRecycled()){
				selPhoto.setImageBitmap(bitmap);
			}else{
				selPhoto.setImageResource(R.drawable.default_photo);
			}
			
 			  Time time = new Time();
			  time.set(this.mylocUpdateTime);
			  String timeS = time.format("%Y-%m-%d %H:%M");
			  updateTimeTxt.setText(getResources().getString(R.string.update_at,timeS));				
        	
            refreshBut.setVisibility(View.GONE); 
        	allLL.setVisibility(View.GONE);
        	singleDevLL.setVisibility(View.VISIBLE);
        	sigleModeButPan.setVisibility(View.GONE);
        	isSingleTidMapMode = true;
        	sosOnTitle.setVisibility(View.GONE);
    	}
    	else
    	{
    	LatLng cenpt = null;
    	scaleManager myScale = new scaleManager();   
        if(mySiteMarker != null)
        {
        	mySiteMarker.remove();
        	mySiteMarker = null;
        }

        Set<String> mapSet =  siteStore.keySet();	//获取所有的key值 为set的集合
		Iterator<String> itor =  mapSet.iterator();//获取key的Iterator便利
		while(itor.hasNext()){//存在下一个值        
			String id = itor.next();
			LOC_DETAIL s = siteStore.get(id); 
			
    		if(id.equals(tid))
    		{ 
    		      cenpt = new LatLng(s.lat,s.lng); 
    			  //titleLocTip.setVisibility(View.VISIBLE);   				  
    			  titleLocTxt.setVisibility(View.VISIBLE);
    			  titleLocTxt.setText(s.addr);
    			  
    			 // String n = this.getResources().getString(R.string.Name);
    			 // NameTxt.setText(n + " " + getDevName(tid));
    			  
    			  Time time = new Time();
    			  time.set(s.time);
    			  String timeS = time.format("%Y-%m-%d %H:%M");
    			  updateTimeTxt.setText(getResources().getString(R.string.update_at,timeS));	
    				
    		}
    		else
    		{
    			devDis dd = disStore.get(id);
    			dd.mark.remove();
    			//devLL.removeView(dd.viewInLL);
    		}			
		}
		mLocClient.stop(); 
    	mBaiduMap.setMyLocationEnabled(false);
   	
    	myScale.myloc = cenpt;
    	
		clearPolyline();
		
		ArrayList<LatLng> points = new ArrayList<LatLng>();
		
		String[] args = new String[1];
        args[0] = tid;
		
        LOCATION_INFO[] arr = (LOCATION_INFO[]) mApp.getDataManager().checkData(DataManager.F_DEVICE_LOCATION, args);
		
		if((arr != null) && (arr.length > 0)){
			try {												
				LOCATION_INFO data = arr[0];
                
				JSONArray mLocArray = data.createJSONArray();	
				if(mLocArray != null)
				for(int i = 0;i<mLocArray.length();i++)
				{	
				JSONObject addrInfoLate = mLocArray.getJSONObject(i);
				Double lat = Double.parseDouble(addrInfoLate.getString("lat"));
				Double lng = Double.parseDouble(addrInfoLate.getString("lng"));
				LatLng p = new LatLng(lat,lng);
				points.add(p);
				myScale.addPoint(p);
				}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
			if(points.size()>1){
			 
			 OverlayOptions polylineOp = new PolylineOptions().width(10)
						.color(Color.BLUE).points(points);
			 mPolyline = mBaiduMap.addOverlay(polylineOp);

			}
		}
    	
		myScale.updateMap();
		
		NameTxt.setText(getDevName(tid));
		String[] fargs = new String[1];
		fargs[0] = tid;
		DEV_FACE face = (DEV_FACE) mApp.getDataManager().checkData(DataManager.F_DEVICEFACE, fargs);
		if(face == null){
			selPhoto.setImageResource(R.drawable.default_photo);
		}else if((face.bitmap != null) && !face.bitmap.isRecycled()){
			selPhoto.setImageBitmap(face.bitmap);
		}else{
			selPhoto.setImageResource(R.drawable.default_photo);
		}
        //定义地图状态
        //MapStatus mMapStatus = new MapStatus.Builder().target(cenpt).zoom(myScale.getNowScaleLevel()).build();
        //定义MapStatusUpdate对象，以便描述地图状态将要发生的变化
         	    	
        //MapStatusUpdate mMapStatusUpdate = MapStatusUpdateFactory.newMapStatus(mMapStatus);
        //改变地图状态
        //mBaiduMap.setMapStatus(mMapStatusUpdate);    
        //mBaiduMap.animateMapStatus(mMapStatusUpdate);
          
    	allLL.setVisibility(View.GONE);
    	singleDevLL.setVisibility(View.VISIBLE);
    	sigleModeButPan.setVisibility(View.VISIBLE);
    	isSingleTidMapMode = true; 
    	
    	//if(选中的（flag & LOCATION_INFO.FLAG_SOS) == LOCATION_INFO.FLAG_SOS)
    	//	sosOnTitle.setVisibility(View.VISIBLE);
    	//}else{
    	//	sosOnTitle.setVisibility(View.GONE);
    	//}
    	
    	}
    }
    
    private String getDevName(String tid)
    {
    	for(DEV_DATA dev : this.mDevListData)
    	{
    		if(dev.id.equals(tid))
    			return dev.name;
    	}
    	return null;
    }
    
	private String getDevPhNumber(String tid){
		DEV_SET mSetData = null;
		
		String[] args = new String[1];
		args[0] = tid;
		
		DEV_SET[] data = (DEV_SET[]) mApp.getDataManager().checkData(DataManager.F_DEVICE_SETTINGS, args);
		if(data != null){
			mSetData =  data[0];
			return mSetData.mobile;
		}
		return null;
	}   
	
	/*private Bitmap getPicWithPhotograph(Bitmap photo )   
	 {   
	      String tag = "createBitmap";   
	      Log.d( tag, "create a new bitmap" );   
	      if( photo == null )   
	      {   
	          return null;   
	      }
	      
	      Drawable mCounterDrawable = getResources().getDrawable(R.drawable.map_person_bg);  
         Bitmap src = ((BitmapDrawable) mCounterDrawable).getBitmap(); 
         
	      int w = src.getWidth();   
	      int h = src.getHeight();   
	      int ww = photo.getWidth();   
	      int wh = photo.getHeight();   
	      //create the new blank bitmap   
	      Bitmap newb = Bitmap.createBitmap( w, h, Config.ARGB_8888 );//创建一个新的和SRC长度宽度一样的位图   
	      Canvas cv = new Canvas( newb );   
	      //draw src into   
	      cv.drawBitmap( src, 0, 0, null );//在 0，0坐标开始画入src   
	      //draw watermark into   
	      cv.drawBitmap( photo, (w - ww)/2, (h - wh)/2, null );
	      //save all clip   
	      cv.save( Canvas.ALL_SAVE_FLAG );//保存   
	      //store   
	      cv.restore();//存储   
	      return newb;   
	  }*/  
	
	private Handler mhandler = new Handler(){
		@Override
		public void handleMessage(Message msg){
			switch(msg.what){
			case MSG_LOADING_TIMEOUT:{
				//loadingFinish();
			}
			break;
			case MSG_UPDATE_DEV_DISPLAY:
			{
				String tid = msg.getData().getString("tid");
				devDis dd = disStore.get(tid);
				LOC_DETAIL s = siteStore.get(tid);
				if(dd == null)
				{			
					  
					Marker mark = createMarkerAndShow(new LatLng(s.lat,s.lng), tid);
					
					dd = new devDis(tid,/*convertView,*/mark);
					disStore.put(tid, dd);	
										
				}
				else
				{
					dd.mark.remove();
					Marker mark = createMarkerAndShow(new LatLng(s.lat,s.lng), tid);
					dd.mark = mark;
								
				}
								
				scaleMgr.updateMap();	
			}
			break;
			
			case MSG_REMOVE_FAKE_REFRESH:
			{
				refreshBut.clearAnimation();				
				refreshBut.setEnabled(true);
			}
			}
		}
	};
	
	private Overlay mPolyline = null;
	
	private void clearPolyline(){
		if(mPolyline != null){
			 mPolyline.remove();
			 mPolyline = null;
		}
	}
	
}
